package com.viewpagertext.fragments;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.viewpagertext.R;
import com.viewpagertext.adapters.LocalFoldExpandableListviewAdapter;
import com.viewpagertext.constructor.Song;
import com.viewpagertext.help.MediaPlayerHelp;
import com.viewpagertext.utils.LoadLocalMusicUtils;
import com.viewpagertext.utils.LoadSongUtils;
import com.viewpagertext.views.MyRoundedImageView;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class LocalFoldFragment extends Fragment {

    private ExpandableListView expandableListView;
    private LocalFoldExpandableListviewAdapter localFoldExpandableListviewAdapter;
    private List<String> directories;
    private HashMap<String, List<Song>> mp3Files;
    private boolean isPlaying;
    private MediaPlayer mediaPlayer;
    private String csong, csinger, calbum, cduration, cpath;
    private long csize;
    private Bitmap cbitmap;
    private MediaPlayerHelp mMediaPlayerHelp;
    private BottomSheetDialog bottomSheetDialog;
    private MyRoundedImageView localDialogIcon;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_local_fold, container, false);
        expandableListView = view.findViewById(R.id.local_fold_expandable_listview);
        initView();
        return view;
    }

    private void initView() {

        directories = new ArrayList<>();
        mp3Files = new HashMap<>();
        mediaPlayer = new MediaPlayer();

        List<Song> allSongs = LoadLocalMusicUtils.getMusic();
        for (Song song : allSongs) {
            String filePath = song.path;
            String directoryName = new File(filePath).getParentFile().getName();
            if (!directories.contains(directoryName)) {
                directories.add(directoryName);
            }
            List<Song> mp3s = mp3Files.get(directoryName);
            if (mp3s == null) {
                mp3s = new ArrayList<>();
            }
            mp3s.add(song);
            mp3Files.put(directoryName, mp3s);
        }

        localFoldExpandableListviewAdapter = new LocalFoldExpandableListviewAdapter(requireContext(), directories, mp3Files, "fold");
        expandableListView.setAdapter(localFoldExpandableListviewAdapter);

        mMediaPlayerHelp = MediaPlayerHelp.getInstance(getActivity());
        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                String directoryName = directories.get(groupPosition);
                List<Song> songs = mp3Files.get(directoryName);
                if (songs != null && childPosition >= 0 && childPosition < songs.size()) {
                    Song clickedSong = songs.get(childPosition);
                    System.out.println(clickedSong.path);
                    csong = clickedSong.song;//获取歌名
                    csinger = clickedSong.singer;//获取歌手
                    csize = clickedSong.size;//歌曲大小
                    cduration = LoadSongUtils.formatTime(clickedSong.duration);//歌曲时长
                    calbum = clickedSong.album;//歌曲专辑
                    long albumId = clickedSong.albumId;
                    cbitmap = LoadSongUtils.getMusicBitemp(getActivity(), childPosition, albumId);
                    cpath = clickedSong.path;//获得歌曲的地址
                    // 查找子项布局中的元素
                    ImageView imageView = v.findViewById(R.id.localmenu);
                    // 根据不同的元素执行不同的操作
                    if (imageView != null && v == imageView.getParent()) {
                        // 如果点击的是 ImageView，则调用 initDialog()
                        initDialog();
                    } else {
                        // 如果点击的是子项布局的其他部分，则播放歌曲
                        if (isPlaying) {
                            stopMusic(cpath);
                        } else {
                            playMusic(cpath);
                        }
                    }
                }
                return true;
            }
        });

    }

    private void initDialog() {
        View view = View.inflate(getActivity(), R.layout.local_dialog, null);
        TextView dialog_song = view.findViewById(R.id.dialog_song);//歌名
        dialog_song.setText(csong);
        TextView dialog_album = view.findViewById(R.id.dialog_album);//专辑
        dialog_album.setText(calbum);
        TextView dialog_singer = view.findViewById(R.id.dialog_singer);//歌手
        dialog_singer.setText(csinger);
        TextView dialog_singer2 = view.findViewById(R.id.dialog_singer2);//歌手
        dialog_singer2.setText(csinger);
        TextView dialog_time = view.findViewById(R.id.dialog_time);//时长
        dialog_time.setText(cduration);
        TextView dialog_size = view.findViewById(R.id.dialog_size);//歌曲大小
        dialog_size.setText(((new DecimalFormat("#.00")).format(Long.valueOf(csize).floatValue() / 1000000)));
        localDialogIcon = view.findViewById(R.id.localDialogIcon);
        MyRoundedImageView localDialogIcon = view.findViewById(R.id.localDialogIcon);//歌手
        localDialogIcon.setImageBitmap(cbitmap);

        bottomSheetDialog = new BottomSheetDialog(getActivity());
        bottomSheetDialog.setContentView(view);
        bottomSheetDialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//设置BottomSheetDialog圆角
        bottomSheetDialog.show();
    }

    //播放音乐
    public void playMusic(String path) {
        isPlaying = true;
        if (mMediaPlayerHelp.getPath() != null
                && mMediaPlayerHelp.getPath().equals(path)) {
            Toast.makeText(getActivity(), "播放继续", Toast.LENGTH_SHORT).show();
            mMediaPlayerHelp.start();
        } else {
            mMediaPlayerHelp.setPath(path);
            mMediaPlayerHelp.setOnMediaPlayerHelperListener(new MediaPlayerHelp.OnMediaPlayerHelperListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mMediaPlayerHelp.start();
                    Toast.makeText(getActivity(), "播放开始", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    //停止音乐
    public void stopMusic(String path) {
        isPlaying = false;
        if (mMediaPlayerHelp.getPath() != null
                && mMediaPlayerHelp.getPath().equals(path)) {
            mMediaPlayerHelp.pause();
            Toast.makeText(getActivity(), "播放暂停", Toast.LENGTH_SHORT).show();

        } else {
//        itemIvPlay.setVisibility(View.VISIBLE);
            mMediaPlayerHelp.setPath(path);
//            mMediaPlayerHelp.stop();

        }
    }


}